package com.zxt.web.database.config;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.springframework.util.ObjectUtils;

import java.nio.charset.StandardCharsets;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@MappedTypes({String.class})
@MappedJdbcTypes(
        value = {JdbcType.VARCHAR},
        includeNullJdbcType = true
)
public class VarcharEncrypTypeHandler extends BaseTypeHandler<String> {
    private static final byte[] salt;

    public VarcharEncrypTypeHandler() {
    }

    public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {
        if (parameter != null) {
            AES aes = SecureUtil.aes(salt);
            String encrypt = aes.encryptHex(parameter);
            ps.setString(i, encrypt);
        }

    }

    public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String target = rs.getString(columnName);
        return ObjectUtils.isEmpty(target) ? null : SecureUtil.aes(salt).decryptStr(target);
    }

    public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String target = rs.getString(columnIndex);
        return ObjectUtils.isEmpty(target) ? null : SecureUtil.aes(salt).decryptStr(target);
    }

    public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String target = cs.getString(columnIndex);
        return ObjectUtils.isEmpty(target) ? null : SecureUtil.aes(salt).decryptStr(target);
    }

    static {
        salt = "2131sadaksfa23sn".getBytes(StandardCharsets.UTF_8);
    }
}
